from control.models import *
from basic_component_related_management.models import *
import pandas as pd
from django.db import IntegrityError, transaction
import json
from tqdm import tqdm
import traceback
from datetime import datetime
from unit_management.models import *


def init_applicant_property():
    super_admin_entity = User.objects.filter(user_account="superadmin").first()
    unit_file_path = "../final_basic_tables/A076B. PCdata基表-4-应用物性表（20250611R1）-1版.xlsx"
    sheet_name = "应用物性表（最终版）（全）"
    df = pd.read_excel(unit_file_path, sheet_name=sheet_name, skiprows=[0,2], header=0, dtype=str)
    start_row = 0
    num_columns = 28
    selected_data = df.iloc[start_row:, :num_columns].fillna("")
    # print(selected_data)
    # return
    # 先将物性全部创建到常量物性里面
    const_property_entity_list = []
    for index, row in selected_data.iterrows():
        quantity_entity = Quantity.objects.filter(
            quantity_abbreviation= row['sQuantityAbb']).first()
        if quantity_entity == None:
            name = row["sQuantityAbb"]
            print(f"Error: {name} not exist in Quantity")
        const_property_entity = ComponentConstProperty(
            name=row["eAppPropName"],
            name_en=row["eAppPropNameEN"],
            abbreviation=row["eAppPropAbbreviation"],
            quantity=quantity_entity,
            data_type="float",
            common_used=True,
            is_show_in_detail=False,
            description=row["sAppPropDescription"],
            description_en=row["sAppPropDescription"],
            comment=row["eAppPropNameEN"],
            create_person=super_admin_entity,
            modify_person=super_admin_entity,
        )
        const_property_entity_list.append(const_property_entity)

    try:
        with transaction.atomic():
            ComponentConstProperty.objects.bulk_create(const_property_entity_list)
    except Exception as e:
        traceback.print_exc()
 
    print(f"应用物性录入完成，共录入: {len(const_property_entity_list)} 个应用物性")

def init_applicant_property_content():
    init_applicant_property()